<template>
  <div class="flex flex-col">
    <div
      class="flex justify-between items-center border p-3 mb-15px rounded-md"
      style="box-shadow: 4px 4px 6px rgba(0, 0, 0, 0.2)"
    >
      <div class="space-x-10">
        <span>
          当前时间：
          <span class="font-bold text-2xl">{{ countUpTime || '--' }}</span>
        </span>
        <span
          >标段时间：
          <span v-if="resultData?.startTime && resultData?.endTime">
            {{ resultData?.startTime || '--' }}-{{ resultData?.endTime || '--' }}
          </span>
          <span v-else>--/--</span>
        </span>
        <span>保证金：￥{{ resultData?.securityDeposit || 0 }}</span>
        <span
          >交易方式：{{
            getDictLabel(DICT_TYPE.BID_TRADING_WAY, resultData?.tradingWay?.toString())
          }}</span
        >
      </div>
      <div>
        <el-button type="primary" @click="subPage(1)">详情</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>
    <ContentWrap>
      <el-container class="flex justify-between">
        <div>
          <div class="space-x-8 font-bold">
            <span
              class="status"
              :class="{
                'bg-sky-500': resultData?.status === 10,
                'bg-lime-500': resultData?.status === 20,
                'bg-stone-400': resultData?.status === 30,
                'bg-red-500': resultData?.status === 40
              }"
              >{{
                getDictLabel(DICT_TYPE.BID_ACTION_SETIO_SORT, resultData?.status?.toString())
              }}</span
            >
            <span>场次：{{ resultData?.sessionCode || '--' }}</span>
            <span v-if="resultData?.coalName">{{ resultData?.coalName }}</span>
            <span v-else>--</span>
          </div>
          <div class="pt-30px flex items-center">
            <span>倒计时：</span>
            <span v-if="isShowCountDown && countDown" class="text-6xl text-red-700 ml-20px">
              {{ countDownTime }}
            </span>
            <span v-else class="text-6xl text-red-700 ml-20px">--:--</span>
          </div>
        </div>
        <div class="flex">
          <div class="space-y-6 mr-100px">
            <div>
              <span class="text-label"
                >{{ `${resultData?.tradingWay === 3 ? '挂牌' : '起拍'}价` }}：</span
              >
              <span>
                <span v-if="resultData?.startingPrice">
                  ￥{{ resultData?.startingPrice || 0 }}
                </span>
                <span v-else>￥--/--</span>
              </span>
            </div>
            <div>
              <span class="text-label">数量：</span>
              <span>
                <span v-if="isEmpty(resultData?.tradingAmount)">
                  {{ resultData?.tradingAmount || 0 }}吨
                </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">交货周期：</span>
              <span>{{ resultData?.deliveryCycle || '--' }}</span>
            </div>
          </div>
          <div class="space-y-6 mr-100px">
            <div>
              <span class="text-label">最新报价：</span>
              <span class="text-xl text-red-700 font-bold">
                <span v-if="isShowMaxQuotePrice"> ￥{{ maxQuotePrice }} </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">剩余量：</span>
              <span>
                <span v-if="isEmpty(resultData?.overAmount)">
                  {{ resultData?.overAmount || 0 }}吨
                </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">交货地：</span>
              <span>{{ resultData?.deliveryPlace || '--' }}</span>
            </div>
          </div>
          <div
            v-if="resultData?.status === 10"
            v-hasPermi="['bid-client:quotePrice:operation']"
            class="flex justify-center items-center mr-50px"
          >
            <el-button
              v-if="[1, 2].includes(resultData?.tradingWay)"
              :disabled="resultData?.quotePriceButton !== 1"
              type="primary"
              @click="biddingQuotation({ type: 1, data: resultData })"
            >
              报价
            </el-button>
            <el-button
              v-if="resultData?.tradingWay === 3"
              :disabled="resultData?.quotePriceButton !== 1"
              type="primary"
              @click="biddingQuotation({ type: 2, data: resultData })"
            >
              购买
            </el-button>
          </div>
        </div>
      </el-container>
    </ContentWrap>
    <div class="flex-1">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
        :height="'100%'"
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="是否中标" align="center" width="100" fixed="left">
          <template #default="{ row }">
            <el-icon v-if="row.whetherBid === 1" color="#b91c1c" size="20">
              <Flag />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column
          label="标段号"
          align="center"
          prop="markCode"
          min-width="180"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="状态" align="center" prop="status" width="150">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.BID_ACTION_SETIO_SORT" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="coalName" width="150">
        </el-table-column>
        <el-table-column
          :label="`${resultData?.tradingWay === 3 ? '挂牌' : '起拍'}价格(元/吨)`"
          align="center"
          prop="startingPrice"
          width="150"
        />
        <el-table-column label="交易量(吨)" align="center" prop="tradingAmount" width="150" />
        <el-table-column label="报价(元/吨)" align="center" prop="quotationPrice" width="150" />
        <el-table-column label="匹配量(吨)" align="center" prop="bidAmount" width="150">
          <template #default="{ row }">
            <span class="text-red-700">{{ row.bidAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="竞拍时间(开始)" align="center" prop="startTime" min-width="150" />
        <el-table-column label="竞拍时间(结束)" align="center" prop="endTime" min-width="150" />
        <el-table-column label="报价时间" align="center" prop="quotationTime" min-width="200" />
        <el-table-column label="操作" align="center" min-width="170" fixed="right">
          <template #default="{ row }">
            <el-container
              v-hasPermi="['bid-client:quotePrice:operation']"
              v-if="[1, 2].includes(resultData?.tradingWay) && row.status === 10"
            >
              <el-input
                :maxlength="7"
                v-model="quotePrice"
                @keyup.enter="updateQuotation(row)"
                placeholder="报价"
              />
              <el-button link type="primary" :disabled="inputLoading" @click="updateQuotation(row)">
                报价
              </el-button>
            </el-container>
            <el-container
              class="flex justify-center"
              v-hasPermi="['bid-client:quotePrice:operation']"
              v-if="resultData?.tradingWay === 3 && row.status === 10"
            >
              <el-button
                link
                type="primary"
                @click="biddingQuotation({ type: 2, data: resultData })"
              >
                购买
              </el-button>
            </el-container>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <QuotationModel
    ref="quotationModel"
    :maxPrice="maxQuotePrice"
    @success="success"
  ></QuotationModel>
</template>
<script setup lang="ts" name="auctionDetail">
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import * as Utils from '@/utils/dict'
import * as bidding from '@/api/bidding'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/formatTime'
import QuotationModel from './quotationModel.vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { isEmpty } from '@/utils/common'
import Socket from '@/utils/socket'

const { DICT_TYPE, getDictLabel } = reactive(Utils)
const router = useRouter()
const loading = ref(true) // 列表的加载中
const resultData: Record<string, any> = ref(null)
const list = ref([]) // 列表的数据
const countDown = ref(0)
const inputLoading = ref(false)
const isShowCountDown = ref(false)
const countDownTime = computed(() => {
  return formatDate(new Date(countDown.value), 'mm:ss')
})
const countUp = ref(new Date().getTime())
const countUpTime = computed(() => {
  return formatDate(new Date(countUp.value), 'HH:mm:ss')
})
const isBeginBidding = ref(false)
const currentTimer: Record<string, any> = ref(null)
const countdownTimer: Record<string, any> = ref(null)
const quoteRow: Record<string, any> = ref(null)
const curDate = computed(() => {
  return formatDate(new Date(), 'YYYY-MM-DD')
})
const quotePrice = ref()
const maxQuotePrice = ref(0)
const quotationModel = ref()
const route = useRoute()
const rowId = ref()
const message = useMessage()
const { wsCache } = useCache()
const emit = defineEmits(['subPage'])

const isShowMaxQuotePrice = computed(() => {
  return (
    resultData.value?.tradingWay === 1 && resultData.value?.status !== 30 && maxQuotePrice.value
  )
})

let socket = null as any
let isSocket = true

/** 查询列表 */

const getList = async () => {
  loading.value = true
  try {
    const data = await bidding.getCustomerActionDetail({ id: rowId.value })
    resultData.value = data.actionHallTopVO || {}
    if (resultData.value?.currentTime) {
      countUp.value = new Date(`${curDate.value} ${resultData.value?.currentTime}`)?.getTime()
    }
    list.value = data.sectionMessageRespVOS || []
  } finally {
    loading.value = false
  }
}

const countDownHandle = () => {
  countdownTimer.value = setInterval(() => {
    countDown.value -= 1000
    if (countDown.value <= 0) {
      socket?.close()
      console.log('结束计时')
      quotePrice.value = undefined
      maxQuotePrice.value = 0
      isSocket = true
      isShowCountDown.value = false
      clearInterval(countdownTimer.value)
      socket?.close()
    }
  }, 1000)
}

const currentTimeHandle = () => {
  currentTimer.value = setInterval(() => {
    countUp.value += 1000
    if (isStartUpSocket() && isSocket && resultData.value?.tradingWay === 1) {
      console.log('开始连接websocket')
      isSocket = false
      initWebSocket()
    }
    if (getInitTime() === 60 * 1000) {
      isShowCountDown.value = true
      countDown.value = getInitTime()
      console.log('开始计时')
      countDownHandle()
    }
    if (isBeginBidding.value !== isBeginBiddingHandle()) {
      getList()
      console.log('刷新列表')
      if (isCacheCountDown()) {
        isShowCountDown.value = true
        countDown.value = getInitTime()
        console.log('开始计时')
        countDownHandle()
      }
    }
    isBeginBidding.value = isBeginBiddingHandle()
  }, 1000)
}

const isCacheCountDown = () => {
  return isBeginBiddingHandle() && getInitTime() !== 60 * 1000 && getInitTime() > 0
}

const isBeginBiddingHandle = () => {
  const curTime = countUp.value
  return list.value.some((e: Record<string, any>) => {
    const startTime = new Date(`${curDate.value} ${e.startTime}`).getTime()
    const endTime = new Date(`${curDate.value} ${e.endTime}`).getTime()
    return curTime >= startTime && curTime <= endTime
  })
}

const goBack = () => {
  router.push({ path: '/bidManage/biddingHall' })
}

const getCurrentData = () => {
  const curTime = countUp.value
  const item: Record<string, any> = list.value.filter((e: Record<string, any>) => {
    const startTime = new Date(`${curDate.value} ${e.startTime}`).getTime()
    const endTime = new Date(`${curDate.value} ${e.endTime}`).getTime()
    return curTime >= startTime && curTime < endTime
  })[0]
  return item
}

const isStartUpSocket = () => {
  const curTime = countUp.value
  const item: Record<string, any> = getCurrentData()
  if (item?.startTime) {
    const startTime = new Date(`${curDate.value} ${item.startTime}`).getTime()
    return curTime > startTime
  }
  return false
}

const getInitTime = () => {
  const curTime = countUp.value
  const item: Record<string, any> = getCurrentData()
  if (!item) {
    return 0
  }
  const endTime = new Date(`${curDate.value} ${item.endTime}`).getTime()
  const timeDiffer = (endTime - curTime) / 1000
  if (timeDiffer > resultData.value?.countdown) {
    return 0
  }
  return timeDiffer * 1000
}

const biddingQuotation = (data) => {
  quotationModel.value.open(data)
}

const success = () => {
  getList()
}

const updateQuotation = async (row) => {
  quoteRow.value = row
  if (!isQuotationTip()) {
    return
  }
  ElMessageBox.confirm(`确认要修改报价？当前报价${quotePrice.value}元/吨`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (resultData.value?.tradingWay === 1 && quotePrice.value <= maxQuotePrice.value) {
      ElNotification({
        title: '提示',
        message: '当前报价必须大于最高报价',
        type: 'warning'
      })
      return false
    }
    handleQuotePrice(row)
  })
}

const isQuotationTip = () => {
  if (!quoteRow.value) {
    ElNotification({
      title: '提示',
      message: '请输入报价',
      type: 'warning'
    })
    return false
  }

  if (!/^[1-9]\d*$/.test(quotePrice.value) || quotePrice.value >= 10000000) {
    ElNotification({
      title: '提示',
      message: '只允许整数',
      type: 'warning'
    })
    return false
  }

  if (quotePrice.value < quoteRow.value?.startingPrice) {
    ElNotification({
      title: '提示',
      message: '当前报价不能小于起拍价格',
      type: 'warning'
    })
    return false
  }

  if (resultData.value?.tradingWay === 1 && quotePrice.value <= maxQuotePrice.value) {
    ElNotification({
      title: '提示',
      message: '当前报价必须大于最高报价',
      type: 'warning'
    })
    return false
  }

  return true
}

const handleQuotePrice = async (row) => {
  const data = {
    id: row.id,
    quotePrice: quotePrice.value
  }
  try {
    inputLoading.value = true
    await bidding.quotePrice(data)
    quotePrice.value = undefined
    message.success('报价成功')
    getList()
  } finally {
    inputLoading.value = false
  }
}

const subPage = async (index: number) => {
  emit('subPage', index, rowId.value)
}

const initWebSocket = () => {
  const options = {
    url: `${
      import.meta.env.VITE_BASE_URL
    }/websocket/quotePrice/${getAccessToken()}/${getTenantId()}`,
    timer: 10 * 1000,
    reconnect: false,
    params: {
      id: resultData.value?.id,
      userId: wsCache.get(CACHE_KEY.USER)?.user?.id,
      userSource: 1,
      tenantId: getTenantId()
    },
    onmessage
  }
  socket = new Socket(options)
}

const onmessage = (data) => {
  if (data?.data) {
    const suc = JSON.parse(data?.data)
    if (suc?.code === 403) {
      message.notifyWarning(suc?.msg)
      return
    }
    if (suc?.code === 500) {
      message.notifyWarning(suc?.msg)
      return
    }
    if (suc?.code === 0) {
      maxQuotePrice.value = suc?.data?.quotePrice || 0
    }
  }
}

const visibilityChange = () => {
  if (document.visibilityState === 'visible') {
    location.reload()
  }
}

/** 初始化 **/
onMounted(async () => {
  document.addEventListener('visibilitychange', visibilityChange)
  if (route.query.id) {
    rowId.value = route.query.id
    await getList()
    currentTimeHandle()
  }
})

onUnmounted(() => {
  clearInterval(currentTimer.value)
  clearInterval(countdownTimer.value)
  document.removeEventListener('visibilitychange', visibilityChange)
  socket?.close()
})
</script>
<style lang="scss" scoped>
.status {
  font-size: 14px;
  border-bottom-right-radius: 16px;
  border-top-right-radius: 16px;
  @apply px-10px py-6px text-light-50 -ml-20px;
}

.text-label {
  @apply inline-block w-100px text-right;
}
</style>
